package com.lbssoft.gpsbd.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;

import com.lbssoft.gpsbd.model.Result;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.Response;


public class HttpUtil {
	
	 private static final String DEFAULT_CHARSET = "UTF-8";  
     
	 private static final int CONNECT_TIME_OUT = 5000; //链接超时时间5秒
		
	 /** 
     * @description 功能描述: post 请求 
     * @param url 请求地址 
     * @param params 参数 
     * @return 请求失败返回null 
     */  
    public static String put(String url, Map<String, String> params) {  
        AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()  
                .setConnectTimeout(CONNECT_TIME_OUT).build());  
        AsyncHttpClient.BoundRequestBuilder builder = http.preparePut(url);
        builder.setBodyEncoding(DEFAULT_CHARSET);  
        if (params != null && !params.isEmpty()) {  
            Set<String> keys = params.keySet();  
            for (String key : keys) {  
                builder.addQueryParam(key, params.get(key));  
            }  
        }  
        Future<Response> f = builder.execute();  
        String body = null;  
        try {  
            body = f.get().getResponseBody(DEFAULT_CHARSET);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        http.close();  
        return body;  
    }


    /**
     * @description 功能描述: post 请求
     * @param url 请求地址
     * @param params 参数
     * @return 请求失败返回null
     */
    public static Result get(String url, Map<String, String> params) {
        Result result = new Result();
        AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
                .setConnectTimeout(CONNECT_TIME_OUT).build());
        AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
        builder.setBodyEncoding(DEFAULT_CHARSET);
        if (params != null && !params.isEmpty()) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                builder.addQueryParam(key, params.get(key));
            }
        }
        Future<Response> f = builder.execute();
        String body = null;
        try {
            body = f.get().getResponseBody(DEFAULT_CHARSET);
            result.setCode(f.get().getStatusCode());
            result.setData(body);
        } catch (Exception e) {
            e.printStackTrace();

        }
        http.close();
        return result;
    }


//    
//    public static void main(String[] args){
//    	String p = "{\"deviceId\":\"2\",\"type\":\"engineStop\"}";
//    	System.out.println(post(p));
//    }
}
